package com.netty.controller;

import cn.hutool.core.util.StrUtil;
import com.netty.model.entity.User;
import com.netty.services.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation("进入聊天列表")
    @GetMapping("/chat")
    public String chat(String receiverUserId, String sendUserId, ModelMap modelMap) {

        if (receiverUserId.equals(sendUserId)){
            modelMap.addAttribute("errMsg", "自己不能和自己聊天");
            modelMap.addAttribute("sendUserId", sendUserId);
            getUserListPutModelMap(modelMap);
            return "friend_list";
        }

        modelMap.addAttribute("sendUserId", sendUserId);
        modelMap.addAttribute("receiverUserId", receiverUserId);

        return "chat";
    }

    @ApiOperation("获取用户列表")
    @GetMapping("/getUserList")
    public String getUserList(String sendUserId, ModelMap modelMap) {

        // 加载用户列表
        getUserListPutModelMap(modelMap);

        modelMap.addAttribute("sendUserId", sendUserId);

        return "friend_list";
    }

    @ApiOperation("添加用户")
    @PostMapping("/addUser")
    public String addUser(User user, ModelMap modelMap) {

        if (StrUtil.isEmpty(user.getUserName()) && user.getUserId() == null) {
            modelMap.addAttribute("user", user);
            modelMap.addAttribute("errMsg", "用户名和用户id不能同时为空");
            return "index";
        } else if (StrUtil.isNotEmpty(user.getUserName()) && user.getUserId() == null) {
            // 添加用户
            int i = userService.addUser(user);
            modelMap.addAttribute("sendUserId", user.getUserId());
        } else if (StrUtil.isEmpty(user.getUserName()) && user.getUserId() != null) {
            // 标识聊天
            User getByFlag = userService.getUserByUserId(user.getUserId());
            if (getByFlag == null) {
                modelMap.addAttribute("errMsg", "用户id不存在");
                return "index";
            }
            modelMap.addAttribute("sendUserId", getByFlag.getUserId());
        }

        getUserListPutModelMap(modelMap);

        return "friend_list";
    }

    private void getUserListPutModelMap(ModelMap modelMap){
        // 加载用户列表
        List<User> allUser = userService.getAllUser();
        modelMap.addAttribute("userList", allUser);
    }
}
